package www.wen.com.common.lib.data.network

import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.util.SpUtil

/**
 * 添加公共header的拦截器
 */
object AddParamsInterceptorImpl : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        var request : Request = chain.request()
        val requestBuilder = request.newBuilder()
        val accessToken = SpUtil.decodeString(KeyHelper.MMKV_ACCESS_TOKEN)!!
        if (request.url.toUrl().toString().contains(BASIC_URL) && accessToken.isNotBlank()) {
            //这里添加不需要带token也能请求的连接
            if(request.url.toUrl().toString().contains("db-api/general/version/lastVersion")){
                return chain.proceed(request)
            }
            request.headers.forEach {
                requestBuilder.addHeader(it.first,it.second)
            }
            request = requestBuilder.header("Authorization", "Bearer ${SpUtil.decodeString(KeyHelper.MMKV_ACCESS_TOKEN)!!}")
                    .method(request.method, request.body)
                    .build()
        }
        return chain.proceed(request)
    }
}